<?php
#### AUTO FORMAT ###############################################################
function autoFormat($view) {
	if (format('html')) template()->buffer($view);
	else if (format('json')) printJSON(template()->getAssigned());
	else if (format('xml')) printXML(template()->getAssigned());
}

#### FORMAT ####################################################################
function format($type) {
	$extension = explode('.', url(2));
	if (!isset($extension[1])) $extension = 'html';
	else $extension = $extension[1];
	if ($type == $extension) return true;
}

#### PRINT JSON ################################################################
function printJSON($data) { 
	foreach ($data as $key => $value) {
		// For objects returned from the Model library methods	
		if (isset($value->data)) $value = $value->data;
		$array[$key] = (array) $value;
	}
	die(json_encode($array)); 
}

#### PRINT XML #################################################################
function printXML($data, $name = 'data') {
	$xml = new SimpleXMLElement('<'.$name.'></'.$name.'>');
	foreach ($data as $key => $value) {
		// For objects returned from the Model library methods	
		if (isset($value->data)) $value = $value->data;
		if (is_array($value)) {
			foreach ($value as $key2 => $value2) {
				$child = $xml->addChild($key);
				$child->addChild($key2, $value2);
			}
		}
		else $xml->addChild($key, $value);
	}
	die($xml->asXML());
}
?>
